package com.dagit.core;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.dagit.core.impl.MapImpl;
import com.dagit.network.traffic.NetworkEngine;

public class Dagit {
	private static Dagit dagit;
	private static Lock createLock = new ReentrantLock();
	
	
	
	//***************************//
	private Map<Object, DMap<Object, Object>> maps = new  ConcurrentHashMap<Object, DMap<Object, Object>>();
	
	private Configuration config ;
	
	
	@SuppressWarnings("unchecked")
	public static final <K,V> DMap<K, V> getMap(K key){
		if (getInstance().maps.containsKey(key)){
			return (DMap<K, V>)getInstance().maps.get(key);			
		}else{
			DMap<K, V> map = new MapImpl<K, V>(key);
			getInstance().maps.put(key, (DMap<Object, Object>) map);
			return map;
		}
	}
	
	private Dagit(){
		
	}
	
	public static Dagit getInstance(){
		if (dagit != null){
			return dagit;
		}
		try{
			createLock.lock();
			if (dagit == null){
				dagit = new Dagit();
			}
		}finally{
			createLock.unlock();			
		}
		return dagit;
	}
	public static void main(String[] args) {
		if (args.length <1){
			System.out.println("Error arguments not found");
			return;
		}
		Configuration c = new Configuration();
		for (int i = 0; i < args.length; i++) {
			if ("-l".equals(args[i])){
				c.setLogger(args[i+1]);
			}
			if ("-i".equals(args[i])){
				c.addInstance(args[i+1], Integer.parseInt(args[i+2]));
			}
		}
		start(c);
	}
	
	public static void start(Configuration c){
		try {
			getInstance().config = c;
			NetworkEngine.startEngine(dagit.config);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
